﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using ClassLib.Classes.Common;
using ClassLib.UserControl.PopupTree;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraSplashScreen;
using ISumen;
using Sumen.Business;
using Sumen.Business.Model;
using Sumen.Business.Model.Presenter.Actor;
using Sumen.Business.Model.Presenter.Category;
using Sumen.Business.Model.Presenter.Inventory;
using Sumen.Business.Model.Presenter.Sys;
using Sumen_Stock.LookAndFeel.Sumen_System;
using Sumen.Business.Model.Presenter;

namespace Sumen_Stock.LookAndFeel.Inventory
{
    public partial class Frm_Stock_Outward : DevExpress.XtraEditors.XtraForm
    {
        private FromCode _fromCode = FromCode.FrmOutward;
        private List<inventory_details> _inventoryDetailses;
        private bool isChange = false;


        #region Presenter

        private OutwardPresenter _outwardPresenter;
        private InventoryPresenter _inventoryPresenter;
        private CustomerPresenter _customerPresenter;
        private ProductDetailsPresenter _productDetailsPresenter;
        private StockPresenter _stockPresenter;
        private PositionXPresenter _positionXPresenter;
        private DiscountPresenter _discountPresenter;
        private CustomerTypePresenter _customerTypePresenter;
        #endregion


        #region From

        public Frm_Stock_Outward()
        {
            InitializeComponent();
            _outwardPresenter = new OutwardPresenter();
            _inventoryPresenter = new InventoryPresenter();
            _customerPresenter = new CustomerPresenter();
            _productDetailsPresenter = new ProductDetailsPresenter();
            _stockPresenter = new StockPresenter();
            _positionXPresenter = new PositionXPresenter();
            _discountPresenter = new DiscountPresenter();
            _customerTypePresenter = new CustomerTypePresenter();

            _inventoryDetailses = new List<inventory_details>();
            txtDate.EditValue = DateTime.Now;
            var query = new BindingSource(_inventoryDetailses, "");
            gridControl1.DataSource = query;
            buttonsArray1.btnXoa.Text = "Đặt lại";
        }

        private void Frm_Stock_Outward_Load(object sender, System.EventArgs e)
        {
            LoadForm();
        }

        public override void Refresh()
        {
            SplashScreenManager.ShowForm(typeof(WaitForm1));
            base.Refresh();
            LoadForm();
            SplashScreenManager.CloseForm();
        }

        private void Frm_Stock_Outward_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            if (isChange)
            {
                if (!ClsMsgBox.XacNhanDongTab())
                {
                    e.Cancel = true;
                    return;
                } this.Dispose();
            }

        }

        #endregion


        #region Button Event

        private void buttonsArray1_btnEventAdd_click(object sender, System.EventArgs e)
        {
            if (Validation())
            {
                stock_outward pOutward = new stock_outward();
                pOutward.Outw_ID = txtCodeOutward.EditValue + string.Empty;
                pOutward.Outw_Customer_ID = (string)lookUpCustomer.EditValue;
                pOutward.Outw_Customer_Name = txtCusName.EditValue + string.Empty;
                pOutward.Outw_Customer_Address = txtCusAddress.EditValue + string.Empty;
                pOutward.Outw_Customer_Contact = txtCusPhone.EditValue + string.Empty;
                pOutward.Outw_RefDate = txtDate.DateTime;
                pOutward.Outw_ID = txtCodeOutward.EditValue + string.Empty;
                pOutward.Outw_Reason = txtReason.EditValue + string.Empty;
                pOutward.Outw_Description = txtDesc.EditValue + string.Empty;
                pOutward.Outw_RefType = (int)EnumRefType.Outward;
                pOutward.Outw_Stock_id = lookUpStock.EditValue + string.Empty;
                pOutward.Outw_Amount = (decimal)Convert.ToDouble(colAmount.SummaryItem.SummaryValue);
                pOutward.Outw_Payment = (sbyte?)(chkPayment.CheckState == CheckState.Checked ? 1 : 0);
                pOutward.Outw_Actived = 1;
                pOutward.Outw_DiscountRate = Convert.ToInt32(spinDiscount.Value);
                pOutward.Outw_User_ID = ClsPublic.User.User_Username;
                if (_outwardPresenter.Add(_inventoryDetailses, pOutward) > 0)
                {
                    ClsMsgBox.ThongTin("Xuất kho thành công.");
                    ResetForm();
                    
                    ClsPublic.WriteLog(_fromCode, EnumFormStatus.Add, pOutward.Outw_ID, "");
                }
            }
        }

        private void buttonsArray1_btnEventDelete_click(object sender, System.EventArgs e)
        {
            if (ClsMsgBox.XacNhan("Bạn có chắc nạp lại lưới?"))
            {
                _inventoryDetailses.Clear();
            }
        }

        private void buttonsArray1_btnEventPrint_click(object sender, System.EventArgs e)
        {

        }

        private void buttonsArray1_btnEventClose_click(object sender, System.EventArgs e)
        {
            this.Dispose();
        }

        #endregion


        #region Control Event

        private void txtDate_EditValueChanged(object sender, System.EventArgs e)
        {
            LoadCodeOutward();
        }

        private void lookUpStock_EditValueChanged(object sender, EventArgs e)
        {
            LoadInventory(lookUpStock.EditValue + string.Empty);
            LoadPosition(lookUpStock.EditValue + string.Empty);
            LoadCodeOutward();
        }

        private void lookUpCustomer_EditValueChanged(object sender, EventArgs e)
        {
            string sCus = lookUpCustomer.EditValue + string.Empty;
            customer oCus = _customerPresenter.GetById(sCus);

            if (oCus != null)
            {
                txtCusAddress.EditValue = oCus.Cus_Address;
                txtCusPhone.EditValue = oCus.Cus_Phone;
                txtCusName.EditValue = oCus.Cus_FullName;
                discount _discount = _discountPresenter.GetByCustomerType(oCus.Cus_CUSTOMER_TYPE_ID);
                if (_discount != null && _discount.Disc_Actived == 1)
                    spinDiscount.EditValue = _discount.Disc_Percent + string.Empty;
            }
        }

        private void spinDiscount_EditValueChanged(object sender, EventArgs e)
        {
            var summary = (_inventoryDetailses.Sum(p => p.Invd_Amount) *
                          (decimal)(1f - (Convert.ToSingle(spinDiscount.EditValue) / 100f)));
            txtSummary.EditValue =  summary;
        }

        #endregion


        #region Grid Event

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            SetTextSummary();

            isChange = true;
            
        }

        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            int iRow;
            iRow = gridView1.FocusedRowHandle;

            string sProductDetails = gridView1.GetRowCellValue(iRow, colProductDetailsID) + string.Empty;
            string sPosition = gridView1.GetRowCellValue(iRow, colPosition) + string.Empty;
            string sQuantity = gridView1.GetRowCellValue(iRow, colQuantity) + string.Empty;
            string sPrice = gridView1.GetRowCellValue(iRow, colPriceUnit) + string.Empty;

            if (string.IsNullOrEmpty(sProductDetails))
            {
                gridView1.SetColumnError(colProductDetailsID, string.Format("Bạn chưa chọn sản phẩm! ESC để bỏ qua."));
                e.Valid = false;
            }
            ////////////////////////////////////////////////////////////////////////////
            //if (string.IsNullOrEmpty(sPosition) || sPosition == "0")
            //{
            //    gridView1.SetColumnError(colPosition, string.Format("Bạn chưa chọn vị trí lưu trong kho! ESC để bỏ qua."));
            //    e.Valid = false;
            //}
            ////////////////////////////////////////////////////////////////////////////
            if (string.IsNullOrEmpty(sPrice) || sPrice == "0")
            {
                gridView1.SetColumnError(colPriceUnit, string.Format("Bạn chưa nhập giá sản phẩm! ESC để bỏ qua."));
                e.Valid = false;
            }
            ////////////////////////////////////////////////////////////////////////////
            if (string.IsNullOrEmpty(sQuantity) || sQuantity == "0")
            {
                gridView1.SetColumnError(colQuantity, string.Format("Bạn chưa nhập số lượng sản phẩm! ESC để bỏ qua."));
                e.Valid = false;
            }
            ////////////////////////////////////////////////////////////////////////////
            //kiểm tra có lớn số lượng chứa trong kho quui định không
            int quantity = Convert.ToInt32(sQuantity);
            int maPos = Convert.ToInt32(gridView1.GetFocusedRowCellValue(colDesc));
            //position_x_inventory tempX = _positionXPresenter.GetById(maPos);
            if (maPos != null && maPos < quantity)
            {
                gridView1.SetColumnError(colQuantity, "Không đủ số lượng trong kho( chỉ còn " + maPos + ")");
                e.Valid = false;
            }
        }

        private void gridControl1_KeyDown(object sender, KeyEventArgs e)
        {
            int row = gridView1.FocusedRowHandle;
            if ((e.KeyCode == Keys.Delete))
            {
                if (ClsMsgBox.XacNhanXoaThongTin())
                {
                    gridView1.DeleteRow(row);
                    SetTextSummary();
                    isChange = true;
                }
            }
        }

        private void searchLookUpProduct_EditValueChanged(object sender, EventArgs e)
        {
            SearchLookUpEdit edit = sender as SearchLookUpEdit;

            //set position cua trong san phẩm trong kho. Puantity, price mac dinh la 0
            object productName = edit.Properties.View.GetFocusedRowCellValue(colSearchProductName);
            object position = edit.Properties.View.GetFocusedRowCellValue(colSearchPositionID);
            object quantity = edit.Properties.View.GetFocusedRowCellValue(colSearchQuantity);
            object productDetailID = edit.Properties.View.GetFocusedRowCellValue(colSearchProductDetailID);

            gridView1.SetFocusedRowCellValue(colProductName, productName);
            gridView1.SetFocusedRowCellValue(colPosition, position);
            gridView1.SetFocusedRowCellValue(colDesc, quantity);
            gridView1.SetFocusedRowCellValue(colProDetailID, productDetailID);
            //gridView1.SetFocusedRowCellValue(colInvDetailInvID, inventoryID);

            //if (gridView1.GetFocusedRowCellValue(colQuantity) == null) 
            gridView1.SetFocusedRowCellValue(colQuantity, "0");
            //if (gridView1.GetFocusedRowCellValue(colPriceUnit) == null) 
            gridView1.SetFocusedRowCellValue(colPriceUnit, "0");
            //if (gridView1.GetFocusedRowCellValue(colAmount) == null)
            gridView1.SetFocusedRowCellValue(colAmount, "0");

            var abc = edit.Properties.View.FocusedColumn;
            if (abc.Name == "colSearchPrice1" || abc.Name == "colSearchPrice2" || abc.Name == "colSearchPrice3")
            {
                object tempPrice = edit.Properties.View.GetFocusedRowCellValue(abc);
                gridView1.SetFocusedRowCellValue(colPriceUnit, tempPrice);
            }
        }

        private void repositoryItemSearchLookUpEdit1View_FocusedColumnChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs e)
        {
            GridView edit = sender as GridView;

            //add giá sỉ loại 1, loại 2 và lẻ
            //var v = new { Price, Name };
            var abc = edit.FocusedColumn;
            if (abc.Name == "colSearchPrice1" || abc.Name == "colSearchPrice2" || abc.Name == "colSearchPrice3")
            {
                object tempPrice = edit.GetFocusedRowCellValue(abc);
                gridView1.SetFocusedRowCellValue(colPriceUnit, tempPrice);
            }
        }

        private void calcQuantity_EditValueChanged(object sender, EventArgs e)
        {
            CalcEdit edit = sender as CalcEdit;
            if (gridView1.GetFocusedRowCellValue(colPriceUnit) == null)
            {
                gridView1.SetFocusedRowCellValue(colPriceUnit, "0");
            }
            string sPrice = gridView1.GetFocusedRowCellValue(colPriceUnit).ToString();
            string sQuantity = edit.EditValue + string.Empty;
            double pri = double.Parse(sPrice == "" || sPrice == null ? "0" : sPrice);
            double quantity = double.Parse(sQuantity == "" || sQuantity == null ? "0" : sQuantity);
            //set gia trị mặc định là 0
            if (edit.EditValue == null) edit.EditValue = "0";
            //nhân lên thành tiền
            gridView1.SetFocusedRowCellValue(colAmount, pri * quantity);
        }

        private void colcPriceUnit_EditValueChanged(object sender, EventArgs e)
        {
            CalcEdit edit = sender as CalcEdit;
            if (gridView1.GetFocusedRowCellValue(colQuantity) == null)
            {
                gridView1.SetFocusedRowCellValue(colQuantity, "0");
            }
            if (edit.EditValue == null) edit.EditValue = "0";
            string sQuantity = gridView1.GetFocusedRowCellValue(colQuantity).ToString();
            string sPrice = edit.EditValue + string.Empty;
            double pri = double.Parse(sPrice == "" || sPrice == null ? "0" : sPrice);
            double quantity = double.Parse(sQuantity == "" || sQuantity == null ? "0" : sQuantity);
            gridView1.SetFocusedRowCellValue(colAmount, pri * quantity);
        }

        #endregion


        #region Method

        void LoadForm()
        {
            LoadStock();
            LoadCustomer();
            LoadInventory(lookUpStock.EditValue + string.Empty);
            LoadCodeOutward();
        }

        void LoadInventory(string pStockID)
        {
            var list = _inventoryPresenter.GetAllExist(pStockID);
            searchLookUpProduct.DataSource = list.First();
            searchLookUpProduct.View.BestFitColumns();
        }

        void LoadCustomer()
        {
            LoadCustomerType();
            lookUpCustomer.Properties.DataSource = _customerPresenter.GetByKey(1);
        }

        void LoadCustomerType()
        {
            LookUpCusType.DataSource = _customerTypePresenter.GetAll();
        }


        void LoadStock()
        {
            lookUpStock.Properties.DataSource = null;
            lookUpStock.Properties.DataSource = _stockPresenter.GetAll();
        }

        void LoadCodeOutward()
        {
            txtCodeOutward.EditValue = _outwardPresenter.GetNewId(txtDate.EditValue, lookUpStock.EditValue + string.Empty) + string.Empty;
        }


        private void SetTextSummary()
        {
            var summary = (_inventoryDetailses.Sum(p => p.Invd_Amount) *
                                  (decimal)(1f - (Convert.ToSingle(spinDiscount.EditValue) / 100f)));
            txtSummary.EditValue = summary;
        }

        void LoadPosition(string pStockId)
        {
            var list = _positionXPresenter.GetByKey(pStockId);
            //var query = from positionXInventory in list
            //            where positionXInventory.Posx_STOCK_ID == pStockId
            //            select new
            //            {
            //                positionXInventory.Posx_Code_X,
            //                positionXInventory.Posx_ID,
            //                positionXInventory.position_y_inventory.Posy_Code_Y,
            //                positionXInventory.position_range.Range_Code,
            //                QuantityExist = positionXInventory.Posx_Quantity_Max - positionXInventory.Posx_Quantity
            //            };
            lookUpPosition.DataSource = null;
            lookUpPosition.DataSource = list.First();
        }

        private void ResetForm()
        {
            isChange = false;
            lookUpCustomer.EditValue = null;
            txtCusName.EditValue = null;
            txtCusAddress.EditValue = null;
            txtCusPhone.EditValue = null;
            txtReason.EditValue = null;
            txtDesc.EditValue = null;
            gridControl1.DataSource = null;
            _inventoryDetailses.Clear();
            var query = new BindingSource(_inventoryDetailses, "");
            gridControl1.DataSource = query;
            LoadCodeOutward();
            Refresh();
        }

        private bool Validation()
        {
            //kiem tra vi tri trong con trong' khong
            dxErrorProvider1.ClearErrors();
            if (txtCusName.EditValue == null || txtCusName.EditValue == "")
            {
                dxErrorProvider1.SetError(txtCusName, "Vui lòng nhập");
                return false;
            }
            if (txtCusPhone.EditValue == null || txtCusPhone.EditValue == "")
            {
                dxErrorProvider1.SetError(txtCusPhone, "Vui lòng nhập");
                return false;
            }
            ////kiểm tra có lớn số lượng chứa trong kho quui định không
            //int maInventory = Convert.ToInt32(gridView1.GetFocusedRowCellValue(colInvDetailInvID));
            //var listGroupInventoryDetail = from p in _inventoryDetailses
            //                               group p by new { p.Invd_INENTORY_ID } into Grouped
            //                               select new inventory_details()
            //                               {
            //                                   Invd_INENTORY_ID = Grouped.Key.Invd_INENTORY_ID,
            //                                   Invd_Quantity = Grouped.Sum(p => p.Invd_Quantity)
            //                               };
            //var listInventory = searchLookUpProduct.DataSource;
            //var query = from p in listGroupInventoryDetail
            //            join pp in _inventoryPresenter.GetAllExist("") on p.Invd_INENTORY_ID equals pp.Inv_ID into Inners
            //            from inner in Inners
            //            where p.Invd_Quantity > inner.Inv_Quantity
            //            select p;
            //if (query.Any())
            //{
            //    gridView1.SetColumnError(colQuantity, "Không đủ số lượng trong kho.");
            //    return false;
            //}
            if (_inventoryDetailses.Count == 0)
            {
                ClsMsgBox.ThongTin("Vui lòng nhập sản phẩm");
                return false;
            }
            return true;
        }

        #endregion




































    }
}